#include<font_manager.h>

#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_GLYPH_H


static FT_Face g_tFace;

static int FreeTypeFontInit(char *aFineName)
{
	int error;
    FT_Library    library;
	int DefaultFont_size = 24;

	/* 初始化 freetype 库 */
	error = FT_Init_FreeType(&library);  
	if (error)
	{
		printf("FT_Init_FreeType err\n");
		return -1;
	}
	
    /* 加载字体文件，保存在&g_tFace中 */
    error = FT_New_Face( library, aFineName, 0, &g_tFace);
	if (error)
	{
		printf("FT_New_Face err\n");
		return -1;
	}
	
    FT_Set_Pixel_Sizes(	 g_tFace, DefaultFont_size, 0);

	return 0;
}

static int FreeTypeSetFontSize(int iFontSize)
{
	FT_Set_Pixel_Sizes(g_tFace, iFontSize, 0);
	return 0;
}

static int FreeTypeGetFontBitMap(unsigned int dwCode, PFontBitMap ptFontBitMap)
{
	int error;
	FT_Vector pen;//origin
	
	FT_GlyphSlot slot = g_tFace->glyph; /* 插槽: 字体的处理结果保存在这里:含glyph和位图 */
	
	pen.x = ptFontBitMap->iCurOriginX * 64;  /* 单位: 1/64 像素 */
	pen.y = ptFontBitMap->iCurOriginY * 64;
	
	/* 移动或旋转 */
	FT_Set_Transform(g_tFace, 0, &pen);      

	/* 根据dwCode加载字符: 得到新的glyph和位图，放到slot,(擦除之前的slot) */
    error = FT_Load_Char(g_tFace, dwCode, FT_LOAD_RENDER);
    if (error)
    {
        printf("FT_Load_Char error\n");
        return -1;
    }

	ptFontBitMap->pucBuffer         = slot->bitmap.buffer;
	ptFontBitMap->tRegion.iLeftUpX  = slot->bitmap_left;
	ptFontBitMap->tRegion.iLeftUpY	= ptFontBitMap->iCurOriginY*2 - slot->bitmap_top;
	ptFontBitMap->tRegion.iHeight	= slot->bitmap.rows;
	ptFontBitMap->tRegion.iWidth	= slot->bitmap.width;
	ptFontBitMap->iNextOriginX		= ptFontBitMap->iCurOriginX + slot->advance.x / 64;
	ptFontBitMap->iNextOriginY		= ptFontBitMap->iCurOriginY;
	
	return 0;
}


static FontOpr g_tFreeTypeOpr = {
	.name          = "freetype",
	.FontInit      = FreeTypeFontInit,
	.SetFontSize   = FreeTypeSetFontSize,
	.GetFontBitMap = FreeTypeGetFontBitMap,
};	



void FreeTypeRegister(void)
{
	RegisterFontOpr(&g_tFreeTypeOpr);
}
















